package org.openclinic.service.impl;

import java.util.Date;
import java.util.List;

import org.openclinic.domain.Appointment;
import org.openclinic.domain.MedicalRecord;
import org.openclinic.repository.DocumentRepository;
import org.openclinic.repository.MedicalRecordRepository;
import org.openclinic.service.MedicalRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MedicalRecordServiceImpl implements MedicalRecordService {
	
	@Autowired
	private DocumentRepository documentRepository;
	
	@Autowired
	private MedicalRecordRepository medicalRecordRepository;
	
	@Override
	public void delete(long id) {
		medicalRecordRepository.delete(id);
	}
	
	@Override
	public List<MedicalRecord> findByCustomer(long customerId) {
		List<MedicalRecord> history = medicalRecordRepository.findByAppointmentCustomerUserId(customerId);
		for (MedicalRecord record : history) {
			record.setPrescribes(documentRepository.findByAppointmentAppointmentIdAndType(record.getAppointment().getAppointmentId(), 1));
			record.setAttests(documentRepository.findByAppointmentAppointmentIdAndType(record.getAppointment().getAppointmentId(), 2));
		}
		
		return history;
	}
	
	@Override
	public MedicalRecord save(MedicalRecord medicalRecord) {
		return medicalRecordRepository.save(medicalRecord);
	}
	
	@Override
	public MedicalRecord save(long appointmentId, String description) {
		MedicalRecord medicalRecord = new MedicalRecord();
		medicalRecord.setAppointment(new Appointment(appointmentId));
		medicalRecord.setDescription(description);
		medicalRecord.setCreationDate(new Date());
		
		medicalRecord = save(medicalRecord);
		medicalRecord.setPrescribes(documentRepository.findByAppointmentAppointmentIdAndType(medicalRecord.getAppointment().getAppointmentId(), 1));
		medicalRecord.setAttests(documentRepository.findByAppointmentAppointmentIdAndType(medicalRecord.getAppointment().getAppointmentId(), 2));		
		
		return medicalRecord;
	}
}
